 <template>
  <div>
    <el-button
      class="filter-item add-style"
      style="margin-left: 10px;"
      type="primary"
      size="mini"
      icon="el-icon-edit"
      @click="clearInput"
    >添加</el-button>

    <tTable :columns="columns" :data="list">
      <!-- 是否已激活 -->
      <template v-slot:cover="slotProps">
        <img class="coverImg" :src="downImgHost + '/' + slotProps.scope.row.cover" alt>
      </template>

      <!-- 交易金额 -->
      <template v-slot:operate="slotProps">
        <el-button
          type="danger"
          class="delete-style"
          @click="deleteRow(slotProps.scope.row.id)"
          size="mini"
          slot="reference"
        >移除</el-button>
        <el-button
          type="primary"
          class="add-style"
          @click="editRow(slotProps.scope.$index)"
          size="mini"
          slot="reference"
        >编辑</el-button>
        <el-button @click="editPrice(slotProps.scope.row.id)" size="mini" slot="reference">编辑价格</el-button>
      </template>
    </tTable>

    <el-dialog :title="isEdit ? '编辑课程' : '添加新课程'" :visible.sync="dialogVisible" width="60%">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="课程名称">
          <el-input
            placeholder="添加课程"
            v-model="formData.name"
            style="width: 200px;"
            class="filter-item"
          />
        </el-form-item>

        <el-form-item label="课程描述">
          <el-input
            type="textarea"
            placeholder="课程描述"
            rows="8"
            v-model="formData.brief"
            style="width: 500px;"
            class="filter-item"
          />
        </el-form-item>

        <el-form-item label="封面">
          <!-- 七牛云 -->
          <!-- <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            accept=".gif, .jpg, .jpeg, .bmp, .png"
            :data="token"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="formData.cover" :src="formData.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>-->
          <!-- 华为云 -->
          <!-- <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            accept=".gif, .jpg, .jpeg, .bmp, .png"
            :headers="token"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="formData.cover" :src="formData.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>-->
          <!-- 本地图片上传 -->
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            accept=".gif, .jpg, .jpeg, .bmp, .png"
            :headers="token"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="formData.cover" :src="downImgHost + '/' + formData.cover" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" class="add-style" @click="confirmBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  createCourse,
  deleteCourse,
  updateCourse,
  getCourse
} from "api/course";
import { creatPrice, getPrice, deletePrice, updatePrice } from "api/course";

import { formatDateTime, tanslateTime } from "src/util/time.js";
import {
  huaweiUploadImageUrl,
  quniuUploadUrl,
  downImgHost,
  quniudownHost,
  uploadImageUrl
} from "src/config/env.js"; // [华为云] [七牛云] [下载地址] [七牛云下载地址] [本地图片上传]
import { getToken } from "src/util/auth";
import { getQiNiuToken } from "src/util/uploadToken";
import { dataOptions } from "src/util/time";
// import Price from "./components/price.vue";
import tTable from "src/components/table/index.vue";

export default {
  data() {
    return {
      list: [],
      loading: true,
      searchData: "",
      dialogVisible: false,
      formData: {
        name: "", // 课程名称
        brief: "", // 课程描述
        cover: "" // 封面
      },
      isEdit: false,

      priceData: {
        amount: "",
        courseId: "",
        effectiveLength: "",
        effectiveLengthUnit: "DAY"
      }, // 新的价格
      timeOptions: dataOptions,
      priceList: [], // 价格列表

      uploadUrl: uploadImageUrl, // 上传封面地址【华为云：huaweiUploadImageUrl】 【七牛云：quniuUploadUrl】【本地：uploadImageUrl】
      token: "", // 图片上传携带的token 【七牛云[在data中添加]】 【华为云[在headers中添加]】
      chooseID: "",
      downImgHost: downImgHost,
      
      columns: [
        {
          attr: { label: "", type: "index", width: "55" }
        },
        {
          attr: { prop: "name", label: "课程名称", width: "100" }
        },
        {
          slot: "cover",
          attr: { prop: "cover", label: "缩略图", width: "120" }
        },
        {
          attr: { prop: "brief", label: "课程描述" }
        },
        {
          attr: { prop: "updateTime", label: "修改时间", width: "100" }
        },
        {
          slot: "operate",
          attr: { label: "操作", width: "260" }
        }
      ]
    };
  },
  components: { tTable },
  mounted() {
    this.setToken(); // 获取图片上传token
    this.getData();
  },
  methods: {
    setToken() {
      this.token = { Authorization: getToken() }; // 图片上传携带的token 【华为云】【本地上传】
      // this.token = { token: getQiNiuToken() }; // 图片上传携带的token 【七牛云】
    },
    // 上传图片返回值【华为云】
    // handleAvatarSuccess(res) {
    //   this.formData.videoCoverObjectId = res.videoCoverObjectId;
    //   this.formData.videoCoverUrl = res.videoCoverUrl;
    //   this.formData.coverExpireTime = res.expireTime;  // 超期时间
    // },

    // 上传图片返回值【七牛云】[返回key,hash地址为永久的]
    // handleAvatarSuccess(res) {
    //   var time = new Date().getTime();
    //   this.formData.cover = quniudownHost + "/" + res.key + "/wm.jpg?" + time;
    // },

    // 上传图片返回值【本地】[返回name,永久]
    handleAvatarSuccess(res) {
      if (res.status > 200) {
        this.$message.error(res.message);
      }
      this.formData.cover = res && res.data;
    },

    editRow(index) {
      this.dialogVisible = true;
      this.chooseID = this.list[index].id;
      this.formData.name = this.list[index].name;
      this.formData.brief = this.list[index].brief;
      this.formData.cover = this.list[index].cover;
      this.isEdit = true;
    },
    clearInput() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.formData.name = "";
      this.formData.brief = "";
      this.formData.cover = "";
    },
    confirmBtn() {
      var data = this.formData;
      if (this.isEdit) {
        // 修改
        updateCourse(this.chooseID, data).then(res => {
          this.$message.success("修改成功");
          this.dialogVisible = false;
          this.getData();
        });
      } else {
        // 添加
        createCourse(data).then(res => {
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.getData();
        });
      }
    },
    deleteRow: function(index) {
      this.$confirm("确定删除么？")
        .then(_ => {
          deleteCourse(index).then(res => {
            this.$message.success("课程已删除");
            this.getData();
          });
        })
        .catch(_ => {});
    },
    getData() {
      getCourse().then(res => {
        res = res.map(item => {
          item.updateTime = formatDateTime(item.updateTime);
          item.isDelete = false;
          return item;
        });
        this.list = res;
        this.loading = false;
      });
    },
    editPrice(id) {
      this.$router.push("/project/enterprice/" + id);
    },

    removeCategory(id) {
      this.$confirm("确认删除该项价格么？")
        .then(_ => {
          deletePrice(id).then(res => {
            this.$message.success("删除成功");
            this.getPrice(this.priceData.courseId);
          });
        })
        .catch(_ => {});
    },
    addPrice() {
      this.$refs.priceData.validate(val => {
        if (val) {
          let priceData = this.priceData;
          if (priceData.effectiveLengthUnit === "FOREVER") {
            delete priceData.effectiveLength;
          }

          creatPrice(priceData).then(res => {
            this.$message.success("添加成功");
            this.getPrice(this.priceData.courseId);
          });
        } else {
          return false;
        }
      });
    },
    changePrice(item, index) {
      if (item.name === item.newName) {
        this.priceList[index].isEdit = false;
      } else {
        updatePrice(item.id, item.newName).then(res => {
          this.$message.success("修改成功");
          this.getPrice(this.priceData.courseId);
        });
      }
    },
    getPrice(id) {
      getPrice(id).then(res => {
        this.priceList = res.map(item => {
          item.time = tanslateTime(
            item.effectiveLength,
            item.effectiveLengthUnit
          );
          item.isEdit = false;
          item.checked = false;
          item.newName = item.name;
          return item;
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "src/style/mixin";
.tabList {
  @include fj(flex-start);

  .tabItem {
    padding-left: 20px;
  }
}
.coverImg {
  width: 100px;
  height: 100px;
}
//----------------封面上传---------------
.avatar-uploader {
  // border: 1px dashed #d9d9d9;
  // border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 2px dotted #f1f1f1;
  border-radius: 10px;
  width: 140px;
  height: 140px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 40px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  line-height: 140px;
  text-align: center;
}
.avatar {
  width: 140px;
  height: 140px;
  display: block;
}
//----------------封面上传---------------
</style>
